﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Suucha.Expressions
{
    public class DynamicCastType
    {
        static MethodInfo castMethod;
        public static object Cast(object obj, Type targetType)
        {
            if (castMethod == null)
            {
                castMethod = typeof(DynamicCastType).GetMethod("CastIt", BindingFlags.NonPublic | BindingFlags.Static);
            }
            return castMethod.MakeGenericMethod(targetType).Invoke(null, new object[] { obj });
        }
        static T CastIt<T>(object obj)
        {
            try
            {
                return (T)obj;
            }
            catch
            {
                return default(T);
            }
        }
    }
}
